package com.zhaiker.keypointestimationlibrary

import android.graphics.RectF
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.lifecycleScope
import com.cv.tnn.model2.FrameInfo
import com.zhaiker.keypointestimation.KPLandMark
import com.zhaiker.keypointestimation.KeypointEstimationHelper
import com.zhaiker.keypointestimationlibrary.ui.theme.KeypointEstimationLibraryTheme
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {

    private val viewModel : MainViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Greeting(
                name = "Android",
                modifier = Modifier.padding()
            )
        }

        lifecycleScope.launch {
            //初始化模型
            KeypointEstimationHelper.init(this@MainActivity,1)
        }
    }

    fun onClickBtn(){
        lifecycleScope.launch {
            if(!KeypointEstimationHelper.sdkAvailable){
                Toast.makeText(this@MainActivity,"SDK未加载完成",Toast.LENGTH_SHORT).show()
                return@launch
            }
            val result : Array<FrameInfo> = viewModel.poseDetect(this@MainActivity)
            if(result.isEmpty()){
                Toast.makeText(this@MainActivity,"检测失败",Toast.LENGTH_SHORT).show()
                return@launch
            }
            val rect = RectF(result[0].xmin,result[0].ymin,result[0].xmax,result[0].xmax)
            Log.i("PoseDetect","score[0]=${result[0].score},box=${rect.toString()}")
            val leftHip = result[0].keypoints[KPLandMark.LEFT_HIP].point
            Log.i("PoseDetect","leftHipX=${leftHip.x},y=${leftHip.y}")
            Toast.makeText(this@MainActivity,"score[0]=${result[0].score}",Toast.LENGTH_SHORT).show()
        }

    }

}


@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    val context = LocalContext.current
    Column {
        Text(
            text = "Hello $name!",
            modifier = modifier
        )

        Button(

            onClick = {
//                Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show()
                (context as MainActivity).onClickBtn()
            },
            modifier = modifier
        ) {
            Text("Test")
        }
    }

}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    KeypointEstimationLibraryTheme {
        Greeting("Android")
    }
}